<template>
  <div>
    <BasicModal
      @register="registerModal"
      v-bind="$attrs"
      @ok="handleSubmit"
      ok-text="保存"
      title="将实体视图分配给客户"
      :closeFunc="handleClose"
    >
      <BasicForm @register="registerForm" />
    </BasicModal>
  </div>
</template>

<script setup lang="ts">
  import { defineEmits, ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { customerSchemas } from './customerModal.data';
  import { modalFormStyleSetting, modalStyleSetting } from '/@/settings/thingsBoardDesign';
  const emit = defineEmits(['success', 'register']);
  const key = ref('');
  let viewId = '';
  let checkedKeys = [];
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({
      ...modalStyleSetting,
    });
    if (data?.key == 'selected') {
      key.value = data.key;
      checkedKeys = data.checkedKeys;
    } else {
      viewId = data.record.id;
    }
  });

  const [registerForm, { validate, resetFields }] = useForm({
    layout: 'vertical',
    schemas: customerSchemas,
    showActionButtonGroup: false,
    ...modalFormStyleSetting,
  });

  async function handleClose() {
    resetFields();
    return true;
  }
  async function handleSubmit() {
    const values = await validate();
    setModalProps({ confirmLoading: true });
    closeModal();
    resetFields();
    if (key.value == 'selected') {
      emit('success', {
        key: 'selectedAssign',
        values: { customerId: values.customer, checkedKeys },
      });
    } else {
      emit('success', { key: 'assign', values: { customerId: values.customer, viewId } });
    }
    key.value = '';
    setModalProps({ confirmLoading: false });
  }
</script>
